package com.woniu.user.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static String secrt = "asdasfasfqwwqwdasdq123qeqwrwqeqfsfgaweweqr";
    private static Integer defaultTime = 60 * 2;

    /**
     * 创建token
     * @param value 自定义数据
     * @param time 过期时间分钟
     * @return
     */
    public static String create(Map<String, Object> value, Integer time) {
        Key key = Keys.hmacShaKeyFor(secrt.getBytes());
        JwtBuilder jb = Jwts.builder();
        if (value != null && value.size() > 0) jb.setClaims(value);
        if (time == null) time = defaultTime;
        return jb.setExpiration(new Date(System.currentTimeMillis() + time * 60 * 1000)).signWith(key).compact();
    }

    public static String create(Integer time){
        return create(null,time);
    }
    public static String create(Map<String,Object> value){
        return create(value,null);
    }
    public static String create(){
        return create(null,null);
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parse(String token){
        Key key = Keys.hmacShaKeyFor(secrt.getBytes());
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
    }

    /**
     * 从登陆后的token取出用户id
     * @return
     */
//    public static Integer getUserId(){
//        Cookie[] cookies = WebUtil.getRequest().getCookies();
//        String token = null;
//        //获取cookie里面的token
//        if (cookies!=null&&cookies.length>0){
//            for (Cookie cookie : cookies) {
//                if (cookie.getName().equals("com.woniuxy.com-token")) {
//                    token = cookie.getValue();
//                    break;
//                }
//            }
//        }
//        try {
//            Integer userId = (Integer) parse(token).get("userId");
//            return userId;
//        }catch (Exception e){
//            throw new UserException("未登录",401);
//        }
//    }
}
